package cn.com.gridinfo.sooc.utils.widget.textview;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.widget.TextView;

import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.ImageGetterUtil;
import com.squareup.picasso.Transformation;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import cn.com.gridinfo.sooc.R;

/**
 * Created by Michelle on 2015/7/7.
 * 处理textview 显示html 图片
 */
public class HtmlImageGetterUtil extends ImageGetterUtil {
    Context mContext;
    TextView mContentText;
    private int height = 0;
    private static float density = 1;


    public HtmlImageGetterUtil(Context c, TextView t, int height) {
        super(c, t);
        this.mContext = c;
        this.mContentText = t;
        this.height = height;
        this.density = mContext.getResources().getDisplayMetrics().density;
    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public Drawable getDrawable(String source) {
        LevelListDrawable d = new LevelListDrawable();
        new ImageGetterAsync(mContext, mContentText, d, height).execute(source);
        return d;
    }

    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024]; // 用数据装
        int len = -1;
        while ((len = is.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        is.close();
        return outstream.toByteArray();
    }

    public static class ImageGetterAsync extends AsyncTask<Object, Void, Bitmap> {

        LevelListDrawable listDrawable;
        Context context;
        TextView textView;
        int height;
        private static final int MAX_WIDTH = 1024;
        private static final int MAX_HEIGHT = 768;

        int size = (int) Math.ceil(Math.sqrt(MAX_WIDTH * MAX_HEIGHT));


        public ImageGetterAsync(Context ctx, TextView tv, LevelListDrawable lv, int height) {
            this.context = ctx;
            this.textView = tv;
            this.listDrawable = lv;
            this.height = height;

        }

        @Override
        protected Bitmap doInBackground(Object... params) {
            String source = (String) params[0];
            try {
//                byte[] data = getBytes(new URL(source).openStream());
//                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

                return Arad.imageLoader.load(source).get();
            } catch (MalformedURLException e) {
                return null;
            } catch (IOException e) {
                return null;
            } catch (Exception e) {
                return null;
            }

        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (result != null) {
                listDrawable.addLevel(1, 1, new BitmapDrawable(context.getResources(), result));
                if (height != 0) {
                    height = new Float(height * density).intValue();
                    height = result.getHeight() > height ? height : result.getHeight();
                    int width = result.getWidth() * height / result.getHeight();
                    listDrawable.setBounds(0, 0, width, height);
                } else {
                    int contentWidth = ((Activity)context).getWindowManager().getDefaultDisplay().getWidth()
                            -context.getResources().getDimensionPixelSize(R.dimen.edge_margin)*2;
                    if (contentWidth != 0) {
                        Bitmap source = null;
                        if (result.getWidth() > contentWidth) {
                            int w = result.getWidth();
                            float scale = (float) contentWidth / (float) w;
                            Matrix matrix = new Matrix();
                            matrix.postScale(scale, scale);
                            source = Bitmap.createBitmap(result, 0, 0, result.getWidth(), result.getHeight(), matrix, true);
                        } else {
                            source = result;
                        }
                        listDrawable.setBounds(0, 0, source.getWidth(), source.getHeight());
                    }
                }
                listDrawable.setLevel(1);
                CharSequence text = textView.getText();
                textView.setText(text);

            }
        }
    }

    static class BitmapTransform implements Transformation {

        int maxWidth;
        int maxHeight;

        public BitmapTransform(int maxWidth, int maxHeight) {
            this.maxWidth = maxWidth;
            this.maxHeight = maxHeight;
        }

        @Override
        public Bitmap transform(Bitmap source) {
            int targetWidth, targetHeight;
            double aspectRatio;

            if (source.getWidth() > source.getHeight()) {
                targetWidth = maxWidth;
                aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                targetHeight = (int) (targetWidth * aspectRatio);
            } else {
                targetHeight = maxHeight;
                aspectRatio = (double) source.getWidth() / (double) source.getHeight();
                targetWidth = (int) (targetHeight * aspectRatio);
            }

            Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
            if (result != source) {
                source.recycle();
            }
            return result;
        }

        @Override
        public String key() {
            return maxWidth + "x" + maxHeight;
        }

    }

    ;
}
